package com.xinqi.common.mybatis.type;

import com.xinqi.common.base.enums.BaseEnum;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * 已定义类型转换，支持 {@link BaseEnum} 接口
 *
 * @author linkai
 * @date 2022/11/25
 */
public class BasicEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    private final Class<E> type;

    private final E[] enums;

    public BasicEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
        this.enums = type.getEnumConstants();
        if (this.enums == null) {
            throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (parameter instanceof BaseEnum) {
            BaseEnum o = (BaseEnum) parameter;
            ps.setString(i, o.getCode());
        } else {
            ps.setString(i, parameter.name());
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String code = rs.getString(columnName);
        return toEnum(code);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String code = rs.getString(columnIndex);
        return toEnum(code);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String code = cs.getString(columnIndex);
        return toEnum(code);
    }

    private E toEnum(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        code = code.trim();
        try {
            if (BaseEnum.class.isAssignableFrom(type)) {
                for (E e : enums) {
                    BaseEnum o = (BaseEnum) e;
                    if (Objects.equals(o.getCode(), code)) {
                        return e;
                    }
                }
                throw new IllegalArgumentException(
                    "Cannot convert " + code + " to " + type.getSimpleName() + " by code value.");
            } else {
                return EnumUtils.getEnum(type, code);
            }
        } catch (Exception ex) {
            throw new IllegalArgumentException(
                "Cannot convert " + code + " to " + type.getSimpleName() + " by ordinal value.", ex);
        }
    }
}
